<template>
  <div class="ai-assistant">
    <el-card class="chat-container">
      <template #header>
        <div class="card-header">
          <span>AI智能医疗小助手</span>
          <el-button type="primary" size="small" @click="clearChat">清空聊天</el-button>
        </div>
      </template>
      
      <div class="chat-messages" ref="chatMessagesContainer">
        <div v-for="(message, index) in chatMessages" :key="index" class="message-item">
          <div :class="['message', message.type === 'user' ? 'user-message' : 'ai-message']">
            <div class="message-avatar">
              <el-icon v-if="message.type === 'user'"><User /></el-icon>
              <el-icon v-else><ChatDotRound /></el-icon>
            </div>
            <div class="message-content">
              <div class="message-text" v-html="message.content"></div>
              <div class="message-time">{{ message.time }}</div>
            </div>
          </div>
        </div>
        
        <!-- 正在输入指示器 -->
        <div v-if="isTyping" class="message-item">
          <div class="message ai-message">
            <div class="message-avatar">
              <el-icon><ChatDotRound /></el-icon>
            </div>
            <div class="message-content">
              <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="chat-input-container">
        <div class="chat-input">
          <el-input
              ref="textareaRef"
              v-model="userInput"
              type="textarea"
              :rows="3"
              placeholder="请输入您的问题..."
              :disabled="isTyping"
              resize="none"
          />
          <div class="input-actions">
            <span class="hint">Enter发送，Ctrl+Enter换行</span>
            <el-button 
              type="primary" 
              @click="sendMessage" 
              :loading="isTyping"
              :disabled="!userInput.trim()"
              size="large"
            >
              发送
            </el-button>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted, onBeforeUnmount, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { User, ChatDotRound } from '@element-plus/icons-vue'
import { aiChat } from '@/api/aiApi'
import { tokenStore } from '@/store'

// 响应式数据
const userInput = ref('')
const isTyping = ref(false)
const chatMessages = ref([])
const chatMessagesContainer = ref(null)
const textareaRef = ref(null)
const memoryId = ref(Math.floor(Math.random() * 1000000))
const token = tokenStore()

// 从本地存储加载聊天记录
const loadChatHistory = () => {
  try {
    const savedMessages = localStorage.getItem('aiAssistantMessages')
    const savedMemoryId = localStorage.getItem('aiAssistantMemoryId')
    
    if (savedMessages) {
      chatMessages.value = JSON.parse(savedMessages)
    }
    
    if (savedMemoryId) {
      memoryId.value = parseInt(savedMemoryId)
    }
  } catch (error) {
    console.error('加载聊天记录失败:', error)
    chatMessages.value = []
  }
}

// 保存聊天记录到本地存储
const saveChatHistory = () => {
  try {
    localStorage.setItem('aiAssistantMessages', JSON.stringify(chatMessages.value))
    localStorage.setItem('aiAssistantMemoryId', memoryId.value.toString())
  } catch (error) {
    console.error('保存聊天记录失败:', error)
  }
}

// 监听聊天记录变化并保存
watch(chatMessages, () => {
  saveChatHistory()
}, { deep: true })

// 监听memoryId变化并保存
watch(memoryId, () => {
  saveChatHistory()
})

// 监听token变化，如果token被清除则清空聊天记录
watch(() => token.token, (newToken) => {
  if (!newToken) {
    clearChatHistory()
  }
})

// 清除聊天记录（不触发保存）
const clearChatHistory = () => {
  chatMessages.value = []
  memoryId.value = Date.now()
  localStorage.removeItem('aiAssistantMessages')
  localStorage.removeItem('aiAssistantMemoryId')
}

// 确保chatMessages始终是一个数组
const addMessage = (message) => {
  console.log('addMessage被调用，参数:', message)
  console.log('当前chatMessages状态:', chatMessages.value)
  console.log('chatMessages类型:', typeof chatMessages.value)
  
  if (!Array.isArray(chatMessages.value)) {
    console.warn('chatMessages不是数组，重新初始化为空数组')
    chatMessages.value = []
  }
  
  chatMessages.value.push(message)
  console.log('添加消息后，chatMessages长度:', chatMessages.value.length)
}

// 发送消息
const sendMessage = async () => {
  if (!userInput.value.trim() || isTyping.value) return
  
  const userMessage = userInput.value.trim()
  const currentTime = new Date().toLocaleTimeString()
  
  // 添加用户消息
  addMessage({
    type: 'user',
    content: userMessage,
    time: currentTime
  })
  
  // 清空输入框
  userInput.value = ''
  
  // 滚动到底部
  await nextTick()
  scrollToBottom()
  
  // 显示AI正在输入
  isTyping.value = true
  
  try {
    // 调用AI接口
    console.log('发送AI请求:', { memoryId: memoryId.value, message: userMessage })
    const response = await aiChat(memoryId.value, userMessage)
    
    // 处理fetch的响应
    console.log('收到AI响应:', response)
    console.log('响应状态:', response.status)
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    // 添加AI消息占位符
    addMessage({
      type: 'ai',
      content: '',
      time: new Date().toLocaleTimeString(),
      isLast: true
    })
    
    // 处理Server-Sent Events流式响应
    let aiResponse = ''
    let buffer = '' // 添加缓冲区处理跨块数据
    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    
    try {
      while (true) {
        const { done, value } = await reader.read()
        if (done) break
        
        const chunk = decoder.decode(value)
        console.log('收到数据块:', chunk)
        
        // 将新数据添加到缓冲区
        buffer += chunk
        
        // 解析完整的行
        const lines = buffer.split('\n')
        // 保留最后一行（可能不完整）
        buffer = lines.pop() || ''
        
        for (const line of lines) {
          if (line.startsWith('data:')) {
            const data = line.slice(5).trim()
            if (data) {
              console.log('解析到数据:', data)
              aiResponse += data
              
              // 实时更新最后一条AI消息
              if (Array.isArray(chatMessages.value) && chatMessages.value.length > 0) {
                const lastMessage = chatMessages.value[chatMessages.value.length - 1]
                if (lastMessage && lastMessage.type === 'ai') {
                  lastMessage.content = aiResponse
                  console.log('更新AI消息内容:', aiResponse)
                  
                  // 每次更新后都滚动到底部，确保新内容可见
                  await nextTick()
                  scrollToBottom()
                }
              }
              
              // 滚动到底部
              await nextTick()
              scrollToBottom()
            }
          }
        }
      }
      
      // 处理缓冲区中剩余的数据
      if (buffer.trim()) {
        console.log('处理缓冲区剩余数据:', buffer)
        if (buffer.startsWith('data:')) {
          const data = buffer.slice(5).trim()
          if (data) {
            console.log('解析到剩余数据:', data)
            aiResponse += data
            
            // 更新最后一条AI消息
            if (Array.isArray(chatMessages.value) && chatMessages.value.length > 0) {
              const lastMessage = chatMessages.value[chatMessages.value.length - 1]
              if (lastMessage && lastMessage.type === 'ai') {
                lastMessage.content = aiResponse
                console.log('更新AI消息内容:', aiResponse)
                
                // 更新后滚动到底部
                await nextTick()
                scrollToBottom()
              }
            }
          }
        }
      }
    } finally {
      reader.releaseLock()
    }
    
    console.log('最终AI回复内容:', aiResponse)
    
    // 如果没有收到任何数据，显示默认消息
    if (!aiResponse.trim()) {
      aiResponse = '抱歉，我没有收到有效的回复。'
      if (Array.isArray(chatMessages.value) && chatMessages.value.length > 0) {
        const lastMessage = chatMessages.value[chatMessages.value.length - 1]
        if (lastMessage && lastMessage.type === 'ai') {
          lastMessage.content = aiResponse
        }
      }
    }
    
    // 移除临时标记
    console.log('chatMessages状态:', chatMessages.value)
    console.log('chatMessages类型:', typeof chatMessages.value)
    console.log('chatMessages是否为数组:', Array.isArray(chatMessages.value))
    
    if (Array.isArray(chatMessages.value)) {
      const lastAiMessage = chatMessages.value.find(msg => msg.type === 'ai' && msg.isLast)
      if (lastAiMessage) {
        delete lastAiMessage.isLast
      }
    } else {
      console.error('chatMessages不是数组，重新初始化')
      chatMessages.value = []
    }
    
    // 滚动到底部
    await nextTick()
    scrollToBottom()
    
  } catch (error) {
    console.error('AI聊天出错:', error)
    ElMessage.error('AI助手暂时无法响应，请稍后重试')
    
    // 添加错误消息
    addMessage({
      type: 'ai',
      content: '抱歉，我暂时无法响应，请稍后重试。',
      time: new Date().toLocaleTimeString()
    })
  } finally {
    isTyping.value = false
    await nextTick()
    scrollToBottom()
  }
}

// 在光标位置插入文本
const insertAtCursor = (textarea, text) => {
  const startPos = textarea.selectionStart
  const endPos = textarea.selectionEnd
  const beforeText = textarea.value.substring(0, startPos)
  const afterText = textarea.value.substring(endPos, textarea.value.length)
  
  textarea.value = beforeText + text + afterText
  textarea.selectionStart = textarea.selectionEnd = startPos + text.length
  
  // 触发input事件更新v-model
  const event = new Event('input', { bubbles: true })
  textarea.dispatchEvent(event)
}

// 处理键盘事件
const handleKeydown = (event) => {
  if (event.key === 'Enter') {
    // 如果按了Ctrl+Enter，插入换行符
    if (event.ctrlKey) {
      event.preventDefault()
      const textarea = event.target
      insertAtCursor(textarea, '\n')
    } 
    // 如果只按了Enter键（没有Ctrl等修饰键），发送消息
    else if (!event.shiftKey && !event.altKey) {
      event.preventDefault() // 阻止默认的换行行为
      sendMessage()
    }
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (chatMessagesContainer.value) {
    // 使用 nextTick 确保DOM更新完成后再滚动
    nextTick(() => {
      if (chatMessagesContainer.value) {
        chatMessagesContainer.value.scrollTop = chatMessagesContainer.value.scrollHeight
        console.log('滚动到底部，scrollTop:', chatMessagesContainer.value.scrollTop, 'scrollHeight:', chatMessagesContainer.value.scrollHeight)
      }
    })
  }
}

// 滚动到指定消息
const scrollToMessage = (messageIndex) => {
  if (chatMessagesContainer.value && messageIndex >= 0) {
    nextTick(() => {
      const messageElements = chatMessagesContainer.value.querySelectorAll('.message-item')
      if (messageElements[messageIndex]) {
        messageElements[messageIndex].scrollIntoView({ 
          behavior: 'smooth', 
          block: 'nearest' 
        })
      }
    })
  }
}

// 清空聊天
const clearChat = () => {
  clearChatHistory()
  ElMessage.success('聊天记录已清空')
}

// 组件挂载后滚动到底部并添加事件监听器
onMounted(() => {
  loadChatHistory()
  scrollToBottom()
  // 添加键盘事件监听器
  nextTick(() => {
    if (textareaRef.value && textareaRef.value.$el) {
      const textarea = textareaRef.value.$el.querySelector('textarea')
      if (textarea) {
        textarea.addEventListener('keydown', handleKeydown)
      }
    }
  })
})

// 组件卸载前移除事件监听器
onBeforeUnmount(() => {
  if (textareaRef.value && textareaRef.value.$el) {
    const textarea = textareaRef.value.$el.querySelector('textarea')
    if (textarea) {
      textarea.removeEventListener('keydown', handleKeydown)
    }
  }
})
</script>

<style scoped>
.ai-assistant {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chat-container {
  height: calc(100vh - 200px);
  display: flex;
  flex-direction: column;
  flex: 1;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  flex-shrink: 0;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px 0;
  min-height: 300px;
  max-height: calc(100vh - 450px);
  margin-bottom: 20px;
}

.message-item {
  margin-bottom: 20px;
}

.message {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.user-message {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f0f8ff;
  color: #409eff;
  flex-shrink: 0;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.user-message .message-avatar {
  background: #409eff;
  color: white;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.message-content {
  flex: 1;
  max-width: 70%;
}

.message-text {
  background: #f5f5f5;
  padding: 16px 20px;
  border-radius: 18px;
  line-height: 1.6;
  word-wrap: break-word;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  font-size: 14px;
}

.user-message .message-text {
  background: #409eff;
  color: white;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 6px;
  text-align: right;
}

.user-message .message-time {
  text-align: left;
}

.chat-input-container {
  margin-top: auto;
  padding: 20px 0;
  border-top: 1px solid #eee;
  background: white;
  position: sticky;
  bottom: 0;
  flex-shrink: 0;
  z-index: 10;
}

.chat-input {
  display: flex;
  flex-direction: column;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
}

.hint {
  font-size: 12px;
  color: #999;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 16px 20px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #409eff;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ai-assistant {
    padding: 10px;
  }
  
  .message-content {
    max-width: 85%;
  }
  
  .message-text {
    padding: 12px 16px;
    font-size: 13px;
  }
  
  .chat-messages {
    max-height: calc(100vh - 400px);
  }
}
</style> 